﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using FarmacieDAL;
using System.ComponentModel;
using Telerik.Windows.Controls;
using Farmacie.Windows;
using Farmacie.Managers;

namespace Farmacie.Controls
{
    /// <summary>
    /// Interaction logic for VanzareControl.xaml
    /// </summary>
    public partial class VanzareControl : UserControl, INotifyPropertyChanged
    {
        private Chitanta chitanta = new Chitanta();

        public VanzareControl()
        {
            InitializeComponent();
            toateMedicamentele = MedicamenteManager.ToateMedicamentele;
            toateSubstantele = Medicament.ToateSubstantele;
            toateUnitatile = Medicament.ToateUnitatile;

            dropDownSubstanta.KeyUp += dropDown_KeyUp;
            dropDownIdSubstanta.KeyUp += dropDown_KeyUp;
            dropDownMedicament.KeyUp += dropDown_KeyUp;

            numericCantitate.ValueChanged += numericCantitate_ValueChanged;
            oldCantitate = numericCantitate.Value;

            buttonOK.Click += buttonOK_Click;
            buttonReteta.Click += new RoutedEventHandler(buttonReteta_Click);
            vanzari = new CollectionViewSource();
            vanzari.Source = vanzari_internal;
            buttonFinalizeaza.Click += buttonFinalizeaza_Click;

            Vanzari.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Vanzari_CollectionChanged);
            this.Loaded += VanzareControl_Loaded;
        }

        void Vanzari_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            buttonFinalizeaza.IsEnabled = !Vanzari.IsEmpty;
        }

        void buttonReteta_Click(object sender, RoutedEventArgs e)
        {
            RetetaWindow retetaWindow = new RetetaWindow(chitanta);
            retetaWindow.Closed += new EventHandler<WindowClosedEventArgs>(retetaWindow_Closed);
            retetaWindow.Show();
        }

        void retetaWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            OnPropertyChanged("TotalCompensat");
            OnPropertyChanged("TotalDePlata");
            OnPropertyChanged("TotalChitanta");
        }

        void VanzareControl_Loaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = this;
        }

        #region Vanzari

        private List<Vanzare> vanzari_internal = new List<Vanzare>();
        private CollectionViewSource vanzari;

        public ICollectionView Vanzari
        {
            get { return vanzari.View; }
        }

        void buttonFinalizeaza_Click(object sender, RoutedEventArgs e)
        {
            foreach (Vanzare vanzare in vanzari_internal)
            {
                chitanta.Detalii_Chitanta.Add(new Detalii_Chitanta() { Vanzare = vanzare });
            }

            chitanta.Data = testDatePicker.SelectedDate.HasValue ? testDatePicker.SelectedDate.Value : DateTime.Now;
            chitanta.Total = vanzari_internal.Sum(x => x.Pret * x.Cantitate);

            var totalDePlata = TotalDePlata;

            FarmacieDALManager.EntitiesContext.AddToChitanta(chitanta);
            FarmacieDALManager.EntitiesContext.SaveChanges();

            IncasariManager.Instance.AdaugaLaIncasari(totalDePlata);
            StocCriticManager.Refresh();
            RefreshControl();

            chitanta = new Chitanta();
        }

        public void RefreshControl()
        {
            vanzari_internal.Clear();
            Vanzari.Refresh();

            OnPropertyChanged("TotalCompensat");
            OnPropertyChanged("TotalDePlata");
            OnPropertyChanged("TotalChitanta");

            MedicamentSelectat = null;
            SubstantaSelectata = null;
            UnitateSelectata = null;
            numericCantitate.Value = 0;

            OnPropertyChanged("TotalCompensat");
            OnPropertyChanged("TotalDePlata");
            OnPropertyChanged("TotalChitanta");
        }

        private void buttonDelete_Sterge(object sender, RoutedEventArgs e)
        {
            RadButton button = sender as RadButton;

            if (button != null)
            {
                Vanzare selectedVanzare = button.DataContext as Vanzare;
                vanzari_internal.Remove(selectedVanzare);
                Vanzari.Refresh();

                OnPropertyChanged("TotalCompensat");
                OnPropertyChanged("TotalDePlata");
                OnPropertyChanged("TotalChitanta");
            }
        }

        public double TotalCompensat
        {
            get
            {
                double total = 0;

                if (chitanta.Reteta != null)
                {
                    foreach (Detalii_Reteta detaliiReteta in chitanta.Reteta.Detalii_Reteta)
                    {
                        total += vanzari_internal.Where(x => x.Medicament.Id_SubstantaActiva == detaliiReteta.Id_SubstantaActiva)
                                                .Sum(x => (x.Cantitate * chitanta.Reteta.Tip_Compensat * x.Pret) / 100);
                    }

                    return total;
                }

                return 0;
            }
        }

        public double TotalDePlata
        {
            get
            {
                return vanzari_internal.Sum(x => x.Cantitate * x.Pret) - TotalCompensat;
            }
        }

        public double TotalChitanta
        {
            get
            {
                return vanzari_internal.Sum(x => x.Cantitate * x.Pret);
            }
        }

        #endregion

        void buttonOK_Click(object sender, RoutedEventArgs e)
        {
            if (progressBar.Value == 100)
            {
                Vanzare newVanzare = new Vanzare();
                newVanzare.Medicament = MedicamentSelectat;
                newVanzare.Pret = MedicamentSelectat.CostVanzare;
                newVanzare.Cantitate = numericCantitate.Value.Value;
                newVanzare.Data = testDatePicker.SelectedDate.HasValue ? testDatePicker.SelectedDate.Value : DateTime.Now;

                vanzari_internal.Add(newVanzare);

                MedicamentSelectat = null;
                SubstantaSelectata = null;
                UnitateSelectata = null;
                numericCantitate.Value = 0;

                Vanzari.Refresh();

                OnPropertyChanged("TotalCompensat");
                OnPropertyChanged("TotalDePlata");
                OnPropertyChanged("TotalChitanta");
            }
        }

        double? oldCantitate;
        void numericCantitate_ValueChanged(object sender, RadRangeBaseValueChangedEventArgs e)
        {
            if (medicamentSelectat != null)
            {
                ValoareTotala = medicamentSelectat.CostVanzare * numericCantitate.Value.Value;
            }
            else
            {
                ValoareTotala = 0;
            }

            if (numericCantitate.Value.HasValue && numericCantitate.Value > 0 && (!oldCantitate.HasValue || oldCantitate == 0))
            {
                IncreaseProgressBar(20);
            }
            else if (numericCantitate.Value.HasValue == false || numericCantitate.Value == 0 && (oldCantitate.HasValue && oldCantitate > 0))
            {
                DecreaseProgressBar(20);
            }

            oldCantitate = numericCantitate.Value;
        }

        void dropDown_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                RadComboBox selectedCombo = sender as RadComboBox;

                if (selectedCombo != null)
                {
                    selectedCombo.SelectedItem = null;
                }
            }
        }

        private Medicament medicamentSelectat;
        private Substanta_Activa substantaSelectata;
        private Unitate_Masura unitateSelectata;

        private List<Medicament> toateMedicamentele;
        private List<Substanta_Activa> toateSubstantele;
        private List<Unitate_Masura> toateUnitatile;

        private double valoareTotala;

        public double ValoareTotala
        {
            get { return valoareTotala; }
            set
            {
                if (value != valoareTotala)
                {
                    valoareTotala = value;
                    OnPropertyChanged("ValoareTotala");
                }
            }
        }

        public Medicament MedicamentSelectat
        {
            get { return medicamentSelectat; }
            set
            {
                if (value != medicamentSelectat)
                {
                    if (value != null && medicamentSelectat == null)
                    {
                        IncreaseProgressBar(20);
                    }
                    else if (value == null && medicamentSelectat != null)
                    {
                        DecreaseProgressBar(20);
                    }

                    medicamentSelectat = value;

                    if (medicamentSelectat != null)
                    {
                        SubstantaSelectata = medicamentSelectat.Substanta_Activa;
                        UnitateSelectata = medicamentSelectat.Unitate_Masura;                              
                        
                        if (numericCantitate.Value.HasValue)
                        {
                            ValoareTotala = medicamentSelectat.CostVanzare * numericCantitate.Value.Value;
                        }
                        else
                        {
                            ValoareTotala = 0;
                        }
                    }

                    OnPropertyChanged("MedicamentSelectat");
                }
            }
        }

        public IEnumerable<Substanta_Activa> ToateSubstantele
        {
            get { return toateSubstantele; }
        }

        public IEnumerable<Medicament> ToateMedicamentele
        {
            get
            {
                IEnumerable<Medicament> medicamenteFiltrate = toateMedicamentele;

                if (substantaSelectata != null)
                {
                    medicamenteFiltrate = medicamenteFiltrate.Where(x => x.Substanta_Activa == substantaSelectata);
                }

                if (unitateSelectata != null)
                {
                    medicamenteFiltrate = medicamenteFiltrate.Where(x => x.Unitate_Masura == unitateSelectata);
                }

                return medicamenteFiltrate;
            }
        }

        public IEnumerable<Unitate_Masura> ToateUnitatile
        {
            get { return toateUnitatile; }
        }

        public Unitate_Masura UnitateSelectata
        {
            get { return unitateSelectata; }
            set
            {
                if (value != unitateSelectata)
                {
                    if (unitateSelectata != null)
                    {
                        MedicamentSelectat = null;
                    }

                    if (value != null && unitateSelectata == null)
                    {
                        IncreaseProgressBar(20);
                    }

                    if (value == null && unitateSelectata != null)
                    {
                        DecreaseProgressBar(20);
                    }

                    unitateSelectata = value;
                    OnPropertyChanged("UnitateSelectata");
                    OnPropertyChanged("ToateMedicamentele");
                }
            }
        }

        public Substanta_Activa SubstantaSelectata
        {
            get { return substantaSelectata; }
            set
            {
                if (value != substantaSelectata)
                {
                    if (substantaSelectata != null)
                    {
                        MedicamentSelectat = null;
                    }

                    if (value != null && substantaSelectata == null)
                    {
                        IncreaseProgressBar(40);
                    }
                    else if (value == null && substantaSelectata != null)
                    {
                        DecreaseProgressBar(40);
                    }

                    substantaSelectata = value;
                    OnPropertyChanged("SubstantaSelectata");
                    OnPropertyChanged("ToateMedicamentele");
                }
            }
        }

        public void IncreaseProgressBar(double value)
        {
            progressBar.Value += value;

            if (progressBar.Value == 100)
            {
                buttonOK.IsEnabled = true;
            }
        }

        public void DecreaseProgressBar(double value)
        {
            progressBar.Value -= value;
            buttonOK.IsEnabled = false;
        }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion
    }
}
